const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();

Page({
  data: {
    recordings: [], // 存储所有录音
    isRecording: false,
    recordTime: 0,
    formattedTime: '00:00',
    timer: null,
    currentPlaying: -1 // 当前正在播放的录音索引
  },

  onLoad() {
    this.setupRecorderListeners();
    this.setupAudioListeners();
  },

  onUnload() {
    this.stopTimer();
    innerAudioContext.stop();
  },

  // --- 设置监听器 ---
  setupRecorderListeners() {
    recorderManager.onStart(() => {
      this.setData({ isRecording: true, recordTime: 0 });
      this.startTimer();
    });

    recorderManager.onStop((res) => {
      this.stopTimer();
      if (res.duration < 1000) {
        wx.showToast({ title: '录音时间太短', icon: 'none' });
        this.setData({ isRecording: false });
        return;
      }
      const newRecording = {
        src: res.tempFilePath,
        duration: Math.round(res.duration / 1000)
      };
      const recordings = this.data.recordings.concat(newRecording);
      this.setData({ recordings, isRecording: false });
    });

    recorderManager.onError((res) => {
      this.stopTimer();
      this.setData({ isRecording: false });
      wx.showToast({ title: '录音失败', icon: 'none' });
    });
  },

  setupAudioListeners() {
    innerAudioContext.onPlay(() => {
      // 播放开始，不需要特别处理
    });
    innerAudioContext.onEnded(() => {
      this.setData({ currentPlaying: -1 });
    });
    innerAudioContext.onStop(() => {
      this.setData({ currentPlaying: -1 });
    });
    innerAudioContext.onError(() => {
      this.setData({ currentPlaying: -1 });
      wx.showToast({ title: '播放失败', icon: 'none' });
    });
  },

  // --- 录音控制 ---
  toggleRecord() {
    if (this.data.isRecording) {
      recorderManager.stop();
    } else {
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.record']) {
            wx.authorize({
              scope: 'scope.record',
              success: () => this.startRecording(),
              fail: () => wx.showModal({ title: '提示', content: '您未授权录音，将无法使用此功能。' })
            });
          } else {
            this.startRecording();
          }
        }
      });
    }
  },

  startRecording() {
    const options = {
      duration: 60000, // 60秒
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 96000,
      format: 'mp3'
    };
    recorderManager.start(options);
  },

  // --- 录音列表操作 ---
  playRecording(e) {
    const index = e.currentTarget.dataset.index;
    const { src } = this.data.recordings[index];

    if (this.data.currentPlaying === index) {
      innerAudioContext.stop();
    } else {
      innerAudioContext.src = src;
      innerAudioContext.play();
      this.setData({ currentPlaying: index });
    }
  },

  deleteRecording(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.currentPlaying === index) {
      innerAudioContext.stop();
    }
    const recordings = this.data.recordings.slice();
    recordings.splice(index, 1);
    this.setData({ recordings });
  },

  // --- 计时器 ---
  startTimer() {
    this.data.timer = setInterval(() => {
      const recordTime = this.data.recordTime + 1;
      this.setData({ recordTime, formattedTime: this.formatTime(recordTime) });
    }, 1000);
  },

  stopTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.data.timer = null;
    }
  },

  formatTime(seconds) {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return `${m < 10 ? '0' + m : m}:${s < 10 ? '0' + s : s}`;
  },

  // --- 提交克隆 ---
  submitClone() {
    if (this.data.recordings.length < 1) {
      wx.showToast({ title: '请至少录制一段音频', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '正在处理... ', mask: true });
    // 模拟上传和AI处理
    setTimeout(() => {
      wx.hideLoading();
      wx.showModal({
        title: '克隆成功 (模拟)',
        content: '您的专属音色已克隆成功！将来可在故事播放页选择使用。',
        showCancel: false,
        confirmText: '太棒了'
      });
    }, 2000);
  }
});
